const { customer } = require('../db/model/index')
const Sequelize = require('sequelize');
const { query } = require('../config/mysqlDb.js');
const { getDateYYYYMMDDHHMMSS, findGenerationNodes, convertToTree, getDateIntSecs, getRandomInt, sendSMSByAli } = require('../utils/utils.js');
const koa2Req = require('koa2-request');
const { WX_CONFIG } = require('../config/db')//微信的配置

const api = {
    getUnionid: 'https://api.weixin.qq.com/sns/jscode2session?'
}


//网路请求
async function requesturl(url) {
    try {
        const response = await koa2Req(url)
        console.log('网络请求结果');
        console.log(response.body);
        return response.body
    } catch (error) {
        console.error(error)
    }
}

//获取微信小程序个人信息
async function getWebAccessToken(code) {
    const url = api.getUnionid + '&appid=' + WX_CONFIG.wxchatAppId + '&secret=' + WX_CONFIG.wxchatSecret + '&js_code=' + code + '&grant_type=authorization_code';
    const data = await requesturl(url)
    console.log('data===', JSON.parse(data).openid);

    let result = '';
    if (JSON.parse(data).openid){
        result = await getUserOpenidServer({ "openid": JSON.parse(data).openid })
        return { "code": 200, "data": result };
    }else{
        return { "code": 300, "data": "code无效" };
    }
}

//验证客户代码的正确性
async function getCustomer(customer) {
    const result = await query('select * from customers where customer = ?', [customer]);
    if (!result[0]) return { "code": 200, "data": null };
    return { "code": 200, "data": result[0] };
}

//用户唯一性判断
async function getUserOpenidServer(data) {
    const { openid, createdAt = getDateYYYYMMDDHHMMSS(), updatedAt = getDateYYYYMMDDHHMMSS() } = data;
    const args = [openid, createdAt, updatedAt];
    const result = await query('select * from users where openid = ?', [openid]);
    let userInfo = '';
    if (result[0]) {
        userInfo = result[0];
        return userInfo;
    } else {
        const rs = await query('INSERT INTO users (openid,createdAt,updatedAt) VALUES (?, ?, ?)', args, true);
        const { insertId: id } = rs;
        return { "openid": openid };
    }
}

//发送手机短信
async function sendCodeAction(data) {
    let tel = data.tel;
    console.log('tel===', tel);
    let code = getRandomInt(6);
    console.log(code);
    sendSMSByAli(tel, code);
    //插入一条数据
    const args = [code, tel, getDateYYYYMMDDHHMMSS(), getDateYYYYMMDDHHMMSS()];
    console.log('args==', args);
    const result = await query('INSERT INTO codes (code, mobile,createdAt,updatedAt) VALUES (?, ?, ?, ?)', args, true);
    const { insertId: id } = result;
    return { "code": 200, "data": id };
}

//提交问答
async function addQuestionAction(ctx) {  
    const { openid, mobile, resutl1, resutl2, resutl3, resutl4,time1,time2,time3,time4, area, customerCode } = ctx.request.body
    const args = [openid, mobile, resutl1, resutl2, resutl3, resutl4, time1, time2, time3,time4,area,customerCode,getDateYYYYMMDDHHMMSS(), getDateYYYYMMDDHHMMSS()];
    const result = await query('INSERT INTO questions (openid, mobile, resutl1, resutl2, resutl3,resutl4,time1,time2,time3,time4, area,customerCode,createdAt,updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', args, true);
    const { insertId: id } = result;
    return { "code": 200, "data": id };
}

//验证码是否过期
async function wechatTelAction(ctx) {  
    const { tel, openid, code, area,createdAt = getDateYYYYMMDDHHMMSS(), updatedAt = getDateYYYYMMDDHHMMSS() } = ctx.request.body;
    console.log(tel + '=======' + openid+'=======' + code+'==========='+area);

    if (area == 'shanghai'){//------------------------上海地区
        //第一步检测短信验证码是否过期
        const list = await query(`SELECT id,code,unix_timestamp(createdAt) AS createdAt FROM codes WHERE mobile=${tel} ORDER BY createdAt DESC`);

        if (list.length > 0) {
            const data = list[0]
            if (Date.now() / 1000 - data.createdAt > 10 * 60) {  /// 10分钟内有效
                console.log("验证码已过期，请重新获取")
                return { "code": 300, "data": '验证码已过期，请重新获取' };
            } else {
                if (data.code == code) {
                    const lt = await query('select * from users where openid = ?', [openid]);
                    console.log(lt);
                    if (lt.length > 0) {
                        //执行修改
                        const ag = [tel, getDateYYYYMMDDHHMMSS(), openid];
                        console.log(ag);
                        let rst = await query('UPDATE users SET mobile=?, updatedAt=? WHERE openid=?', ag);
                        console.log('s==', rst);
                        const { affectedRows } = rst;
                        return { "code": 200, "data": affectedRows };
                    } else {
                        return { "code": 300, "data": 'openid有误' }
                    }
                } else {
                    console.log("验证码错误")
                    return { "code": 300, "data": '验证码错误' };
                }
            }
        } else {
            console.log("未获取到验证码")
            return { "code": 300, "data": '未获取到验证码' };
        }
    }else{//-----------非上海地区----------------------
        return { "code": 200, "data": '非上海地区' };
    }
}
module.exports = {
    getWebAccessToken,
    getCustomer,
    sendCodeAction,
    addQuestionAction,
    wechatTelAction
}